// index.ts
// import type { AxiosResponse } from "axios";
import { ElLoading } from "element-plus";
import Request from "./index";
import { useStore } from "../stores/index";
import { BASE_URL, TIME_OUT } from "./config";

interface LoadingInstance {
  close: () => void;
  [key: string]: any;
}
let loadingInstance: LoadingInstance;

const request = new Request({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptors: (config) => {
      loadingInstance = ElLoading.service({ fullscreen: true });

      const store = useStore();

      // const token = localStorage.getItem("token") as string;
      const token = store.token;

      if (token) {
        config.headers!.Authorization = token;
      }

      return config;
    },
    requestInterceptorsCatch: (err) => {
      return err;
    },
    // 实例响应拦截器
    responseInterceptors: (result) => {
      loadingInstance.close();
      return result;
    },
    responseInterceptorsCatch: (err) => {
      loadingInstance.close();
      return err;
    },
  },
});

// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return request.cancelRequest(url);
};
// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest();
};

export default request;
